﻿using System;
using System.Configuration;
using System.Data;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
namespace ud_gSDMS.project
{
    public partial class project_detail : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string _id;
        private SiteUser _siteUser;
        private int currentUserID = 0;
        
        void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.GetCurrentSiteUser() == null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }
            else
            {
                _siteUser = SiteUtils.GetCurrentSiteUser();
                currentUserID = _siteUser.UserId;
                if (!Page.IsPostBack)
                {
                    PopulateLabels();
                    PopulateControls();
                    if (!string.IsNullOrEmpty(Request["id"]))
                    {
                        _id = Request["id"];
                        LoadData(_id);
                        LoadGridMember(_id);
                    }
                }
            }
            txtNotes.WebEditor.ToolBar = ToolBar.SimpleWithSource;
        }

        private void PopulateLabels()
        {
        }
        private void PopulateControls()
        {
            //var minDay = Convert.ToDateTime(ConfigurationManager.AppSettings["MinDay"]);
            //var maxDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            
            var db = new gSDMS_DataLinq();
            cboProduct_Package_ID.DataValueField = "CAT_Product_Package_ID";
            cboProduct_Package_ID.DataTextField = "Name";
            cboProduct_Package_ID.DataSource = Library.LINQToDataTable(db, db.ud_gSDMS_CAT_PRODUCT_PACKAGEs);
            cboProduct_Package_ID.DataBind();

            cboAccount_Manager.DataValueField = "UserID";
            cboAccount_Manager.DataTextField = "LoginName";
            cboAccount_Manager.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, 6.ToString());
            cboAccount_Manager.DataBind();

            var tbUser = Library.LINQToDataTable(db, db.mp_Users);
            cboAssigned_To.DataValueField = "UserID";
            cboAssigned_To.DataTextField = "LoginName";
            cboAssigned_To.DataSource = tbUser;
            cboAssigned_To.DataBind();

            const bool readOnly = true;
            datContract_Date.ReadOnly = readOnly;
            cboAccount_Manager.Enabled = !readOnly;
            txtCode_Project.ReadOnly = readOnly;
            txtContact_Email_1.ReadOnly = readOnly;
            txtContact_Email_2.ReadOnly = readOnly;
            txtContact_Name_1.ReadOnly = readOnly;
            txtContact_Name_2.ReadOnly = readOnly;
            txtContact_Phone_1.ReadOnly = readOnly;
            txtContact_Phone_2.ReadOnly = readOnly;
            txtContract_Code.ReadOnly = readOnly;
            txtContract_Name.ReadOnly = readOnly;
            txtCustomer_Phone.ReadOnly = readOnly;
            txtCustomer_Code.ReadOnly = readOnly;
            txtCustomer_Email.ReadOnly = readOnly;
            txtCustomer_Fax.ReadOnly = readOnly;
            txtManday.ReadOnly = readOnly;
            //khong cho sua ghi chu
            txtNotes.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            txtNotes.WebEditor.Height = 200;
            txtManday_Actual.ReadOnly = readOnly;
            txtStatus.ReadOnly = readOnly;
            //cboStatus.Enabled = false;
            //cboProject_Leader.Enabled = false;
            txtCustomer_Code.ReadOnly = readOnly;
            txtCustomer_Email.ReadOnly = readOnly;
            txtCustomer_Fax.ReadOnly = readOnly;
            txtCustomer_Name.ReadOnly = readOnly;
            txtCustomer_Phone.ReadOnly = readOnly;
            txtCompany_Address.ReadOnly = readOnly;
            cboAssigned_To.Enabled = !readOnly;
            cboProduct_Package_ID.Enabled = false;
            datEnd_Date.ReadOnly = readOnly;
            datStart_Date.ReadOnly = readOnly;
            datKickoff_Date.ReadOnly = readOnly;
            datEnd_DateProject.ReadOnly = readOnly;
            btnPlan.Visible = false;
            btnApprovePlan.Visible = false;
            btnChangestatus.Visible = false;
            btnFinish.Visible = false;
        }

        private void LoadGridMember(string id)
        {
            var data = gSDMS_BL.getMemberList(_id);
            grdMember.DataSource = data;
            grdMember.DataBind();
        }

        private static string strid;
        // static string 
        private void LoadData(string id)
        {
            if (string.IsNullOrEmpty(id)) return;

            var o = gSDMS_BL.ud_gSDMS_PROJECT_Get(id);

            if (o != null)
            {
                strid = o.Project_ID.ToString();
                hidId.Value = o.Project_ID.ToString();
                hidContractID.Value = o.Contract_ID.ToString();
                //thong tin hop dong
                if (o.CreatedOn != null) hidCreatedOn.Value = o.CreatedOn.Value.ToShortDateString();
                txtContract_Code.Text = o.ud_gSDMS_CONTRACT.Contract_Code;
                txtContract_Name.Text = o.ud_gSDMS_CONTRACT.Contract_Name;
                datContract_Date.Text = o.ud_gSDMS_CONTRACT.Contract_Date.Value.Day + "/" + o.ud_gSDMS_CONTRACT.Contract_Date.Value.Month + "/" + o.ud_gSDMS_CONTRACT.Contract_Date.Value.Year;
                cboProduct_Package_ID.SelectedValue = o.ud_gSDMS_CONTRACT.Cat_Product_Package_ID.ToString();
                datStart_Date.Text = o.ud_gSDMS_CONTRACT.Start_Date.Value.Day + "/" +
                                     o.ud_gSDMS_CONTRACT.Start_Date.Value.Month + "/" +
                                     o.ud_gSDMS_CONTRACT.Start_Date.Value.Year;
                datEnd_Date.Text = o.ud_gSDMS_CONTRACT.End_Date.Value.Day + "/" +
                                   o.ud_gSDMS_CONTRACT.End_Date.Value.Month + "/" + 
                                   o.ud_gSDMS_CONTRACT.End_Date.Value.Year;
                txtManday.Text = o.ud_gSDMS_CONTRACT.Resource.ToString();//lay tu contract o.Resource.ToString();
                txtCustomer_Code.Text = o.ud_gSDMS_CONTRACT.Customer_Code;
                txtCustomer_Name.Text = o.ud_gSDMS_CONTRACT.Customer_Name;
                txtCustomer_Phone.Text = o.ud_gSDMS_CONTRACT.Customer_Phone;
                txtCustomer_Fax.Text = o.ud_gSDMS_CONTRACT.Customer_Fax;
                txtCustomer_Email.Text = o.ud_gSDMS_CONTRACT.Customer_Email;
                txtCompany_Address.Text = o.ud_gSDMS_CONTRACT.Customer_Address;
                txtContact_Name_1.Text = o.ud_gSDMS_CONTRACT.Contact_Name_1;
                txtContact_Email_1.Text = o.ud_gSDMS_CONTRACT.Contact_Email_1;
                txtContact_Phone_1.Text = o.ud_gSDMS_CONTRACT.Contact_Phone_1;
                txtContact_Name_2.Text = o.ud_gSDMS_CONTRACT.Contact_Name_2;
                txtContact_Email_2.Text = o.ud_gSDMS_CONTRACT.Contact_Email_2;
                txtContact_Phone_2.Text = o.ud_gSDMS_CONTRACT.Contact_Phone_2;
                //thong tin tu project
                if (o.ud_gSDMS_CONTRACT.Account_Manager != null) cboAccount_Manager.SelectedValue = o.ud_gSDMS_CONTRACT.Account_Manager.Value.ToString();
                if (o.ud_gSDMS_CONTRACT.Assigned_To != null) cboAssigned_To.SelectedValue = o.ud_gSDMS_CONTRACT.Assigned_To.Value.ToString();
                txtNotes.Text = o.ud_gSDMS_CONTRACT.Notes;
                //lay ten project
                txtCode_Project.Text = o.Name;
                txtManday_Actual.Text = o.Resource.ToString();
                if (o.Kickoff_Date != null) datKickoff_Date.Text = o.Kickoff_Date.Value.Day+"/"+o.Kickoff_Date.Value.Month+"/"+o.Kickoff_Date.Value.Year;
                if (o.End_Date != null) datEnd_DateProject.Text = o.End_Date.Value.Day+"/"+o.End_Date.Value.Month+"/"+o.End_Date.Value.Year;
                txtStatus.Text = o.ud_gSDMS_CAT_PROJECT_PLAN_STATUS.Name;
                //lay file dinh kem...
                BindAttachments();

                //kiem tra user dang nhap
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "11|12|1") && gSDMS_BL.ud_gSDMS_ProjectLeader(strid, _siteUser.UserId.ToString()))
                {
                    btnPlan.Visible = true;
                    btnChangestatus.Visible = true;
                }

                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "12|1"))
                {
                    btnApprovePlan.Visible = true;
                }
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId,"12|1|3|16"))
                {
                    btnFinish.Visible = true;
                }
                if(o.CAT_Project_Step_ID==10)
                {
                    btnApprovePlan.Visible = false;
                    btnChangestatus.Visible = false;
                    btnPlan.Visible = false;
                    btnFinish.Visible = false;
                    lblMes.Visible = true;
                    lblMes.Text = "Dự án này đã hoàn thành...";
                }
                if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "1"))
                {
                    btnApprovePlan.Visible = true;
                    btnChangestatus.Visible = true;
                    btnPlan.Visible = true;
                    btnFinish.Visible = true;
                }
            }
        }

        #region event
        private void BindAttachments()
        {
            if (string.IsNullOrEmpty(hidContractID.Value) == false)
            {
                var repository = new ud_gSDMS_Attachments();
                var item = repository.GetByItemID(OptionForm.Contract.ToString(),hidContractID.Value);
                rptSoftcopy.DataSource = item;
                rptSoftcopy.DataBind();
                lblSoftcopy.Visible = rptSoftcopy.Items.Count > 0;

                /*Lay mot file duy nhat..................
                DataTable tb;
                var repository = new ud_gSDMS_Attachments();
                var items = repository.GetByItemID_Lst(OptionForm.Contract.ToString(), hidContractID.Value);
                foreach (var item in items)
                {
                    rptSoftcopy.DataSource = repository.GetOneObj(item.FileID);
                    rptSoftcopy.DataBind();
                    lblSoftcopy.Visible = rptSoftcopy.Items.Count > 0;
                }*/
            }
        }

        void rptAttachments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + e.CommandArgument;
            path = path.Replace("/", "\\");
            switch (e.CommandName)
            {
                case "DeleteItem":
                    var repository = new ud_gSDMS_Attachments();
                    bool a = repository.DeleteItemAttachment(e.CommandArgument.ToString());
                    bool b = repository.Delete(e.CommandArgument.ToString());
                    if (a && b)
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                    break;
                case "DownloadItem":
                    {
                        var repository_ = new ud_gSDMS_Attachments();
                        var file = repository_.GetOne(Convert.ToInt32(e.CommandArgument));
                        path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + file.ServerFileName;

                        FileInfo f = new FileInfo(path);
                        if (f.Exists)
                        {
                            Response.Clear();
                            Response.ContentType = "application/octet-stream";
                            Response.AddHeader("Content-Disposition",
                                               "attachment; filename=" +
                                               Library.RemoveSign4VietnameseString(file.FileName).Replace(" ", "-"));
                            Response.WriteFile(path);
                            Response.End();
                            //if file does not exist
                        }
                        else
                        {
                            Response.Write("This file does not exist.");
                        }
                        break;
                    }

            }
            WebUtils.SetupRedirect(this, Request.RawUrl);
        }

        void rptAttachments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgType = (Image)e.Item.FindControl("imgType");
            if (imgType == null) return;
            string name = DataBinder.Eval(e.Item.DataItem, "p.FileName", "{0}").Trim();
            // ReSharper disable PossibleNullReferenceException
            var imgFile = Path.GetExtension(name).ToLower().Replace(".", "") + ".png";
            var path = Request.PhysicalApplicationPath + "/Data/SiteImages/Icons/" + imgFile;
            if (File.Exists(path))
            {
                imgType.ImageUrl = ImageSiteRoot + "/Data/SiteImages/Icons/" + imgFile;
            }
            var ibtnDelete = (ImageButton)e.Item.FindControl("ibtnDelete");
        }

        void btnPlan_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strid))
            {
                int id = Convert.ToInt32(strid);
                Response.Redirect("/gSDMSModule/project/plan.aspx?pageid=8&id=" + id);
            }
            // Response.Redirect("/gSDMSModule/project/project_detail.aspx?pageid=16");
        }

        void btnApprovePlan_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strid))
            {
                int id = Convert.ToInt32(strid);
                Response.Redirect("/gSDMSModule/project/approve_plan.aspx?pageid=8&id=" + id);
            }
            // Response.Redirect("/gSDMSModule/project/project_detail.aspx?pageid=16");
        }

        void btnChangestatus_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strid))
            {
                int id = Convert.ToInt32(strid);
                Response.Redirect("/gSDMSModule/project/Changestatus.aspx?pageid=8&id=" + id);
            }
            // Response.Redirect("/gSDMSModule/project/project_detail.aspx?pageid=16");
        }

        void btnFinish_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strid))
            {
                int id = Convert.ToInt32(strid);
                Response.Redirect("/gSDMSModule/project/changesfinish.aspx?pageid=8&id=" + id);
            }
            // Response.Redirect("/gSDMSModule/project/project_detail.aspx?pageid=16");
        }
        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
            btnPlan.Click += new EventHandler(btnPlan_Click);
            btnApprovePlan.Click += new EventHandler(btnApprovePlan_Click);
            btnChangestatus.Click += new EventHandler(btnChangestatus_Click);
            btnFinish.Click +=new EventHandler(btnFinish_Click);
            rptSoftcopy.ItemCommand += rptAttachments_ItemCommand;
            rptSoftcopy.ItemDataBound += rptAttachments_ItemDataBound;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            SuppressPageMenu();
            SiteUtils.SetupEditor(txtNotes);
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion

        protected void txtContract_Code_TextChanged(object sender, EventArgs e)
        {

        }
    }
}